<?php
include_once $_SERVER['DOCUMENT_ROOT']."/controller/connect.php";
include_once $_SERVER['DOCUMENT_ROOT']."/model/Undertake.php";
include_once $_SERVER['DOCUMENT_ROOT']."/model/Stage.php";
include_once "StageDAO.php";
/**
 * Created by PhpStorm.
 * User: lwh
 * Date: 2017/7/21
 * Time: 16:49
 */
class UndertakeDAO{
    const FIELD_ID = "undertakeId";
    const FIELD_USER_ID = "userId";
    const FIELD_STAGE_ID = "stageId";
    const FIELD_START_TIME = "start_time";
    const FIELD_END_TIME = "end_time";
    const FIELD_STATUS = "status";
    const FIELD_CONTRACT_TIME = "contract_time";

    public $conn;

    function __construct()
    {
        $this->conn = new db();
    }

    //插入：$undertake是一个数组
    public function insert($undertake){
        $temp = $this->queryUndertakeStatus($undertake[self::FIELD_USER_ID],$undertake[self::FIELD_STAGE_ID]);
        //之前未接过该任务或者已过期，都可以申请接受该任务
        if($temp == null || $temp->getStatus() == Undertake::$STATUS_EXPIRED){
            $db = $this->conn->getDBConn();
            $stmt = $db->prepare("insert into undertake(userId,stageId,start_time,end_time,status,contract_time) values(?,?,?,?,?,?)");
            $stmt->bindParam(1,$undertake[self::FIELD_USER_ID],PDO::PARAM_INT);
            $stmt->bindParam(2,$undertake[self::FIELD_STAGE_ID],PDO::PARAM_INT);
            $stmt->bindParam(3,$undertake[self::FIELD_START_TIME]);
            $stmt->bindParam(4,$undertake[self::FIELD_END_TIME]);
            $stmt->bindParam(5,$undertake[self::FIELD_STATUS],PDO::PARAM_INT);
            $stmt->bindParam(6,$undertake[self::FIELD_CONTRACT_TIME]);
            $result = $stmt->execute();
            return $result;
        }
        else
            return -1;
    }

    //删除
    public function delete($undertakeId){

    }

    //查询
    public function query($undertakeId){
        $sql = "select * from undertake where ".self::FIELD_ID." = ".$undertakeId;
        $db = $this->conn->getDBConn();
        $row = $db->query($sql)->fetch(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存
        if($row){
            $undertake = $this->loadDataFromResult($row);
            return $undertake;
        }
        else
            return null;
    }

    //更新:传入的undertake是一个对象
    public function update($undertake){
        if($this->query($undertake->getId()) == null)
            return -1;
        //更新操作
        $db = $this->conn->getDBConn();
        $stmt = $db->prepare("update undertake set ".self::FIELD_USER_ID." = ?, ".self::FIELD_STAGE_ID." = ?, ".self::FIELD_START_TIME." = ?, "
            .self::FIELD_END_TIME." = ?, ".self::FIELD_STATUS." = ?, ".self::FIELD_CONTRACT_TIME." = ? where ".self::FIELD_ID." = ?");
        $stmt->bindParam(1,$undertake->getUserId());
        $stmt->bindParam(2,$undertake->getStageId());
        $stmt->bindParam(3,$undertake->getStartTime());
        $stmt->bindParam(4,$undertake->getEndTime());
        $stmt->bindParam(5,$undertake->getStatus());
        $stmt->bindParam(6,$undertake->getContractTime());
        $stmt->bindParam(7,$undertake->getId());
        $result = $stmt->execute();
        return $result;
    }

    //根据用户和状态查询stage列表
    public function queryStageListByUserAndStatus($userId,$status){
        $sql = "select * from undertake where ".self::FIELD_USER_ID." = ".$userId." and ".self::FIELD_STATUS." = ".$status;
        $db = $this->conn->getDBConn();
        $rows = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存
        if(count($rows) > 0){
            $stages = array();
            $stageDAO = new StageDAO();
            foreach ($rows as $row){
                $stage = $stageDAO->query($row[self::FIELD_STAGE_ID]);
                array_push($stages,$stage);
            }
            return $stages;
        }
        else
            return null;
    }

    //根据用户和阶段查询undertake
    public function queryByUserAndStage($userId,$stageId){
        $sql = "select * from undertake where ".self::FIELD_USER_ID." = ".$userId." and ".self::FIELD_STAGE_ID." = ".$stageId;
        $db = $this->conn->getDBConn();
        $row = $db->query($sql)->fetch(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存
		if($row){
		    $undertake = $this->loadDataFromResult($row);
		    return $undertake;
		}
		else
			return null;
    }

    //查询用户最近的一次接任务，以确定是否可以再次接受任务
    public function queryUndertakeStatus($userId,$stageId){
        $sql = "select * from undertake where ".self::FIELD_USER_ID." = ".$userId." and ".self::FIELD_STAGE_ID." = ".$stageId." order by ".self::FIELD_ID." DESC";
        $db = $this->conn->getDBConn();
        $rows = $db->query($sql)->fetchAll(PDO::FETCH_BOTH);//调用查询函数query(),并以关联数组的形式储存
        if(count($rows) > 0){
            $undertake = $this->loadDataFromResult($rows[0]);
            return $undertake;
        }
        else
            return null;
    }

   //查询阶段对应的undertake信息
    public function queryByStage($stageId){
        $sql = "select * from undertake where ".self::FIELD_STAGE_ID." = ".$stageId;
        $db = $this->conn->getDBConn();
        $rows = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);//调用查询函数query(),并以关联数组的形式储存
        if(count($rows) > 0){
            $undertakes = array();
            foreach ($rows as $row){
                $undertake = $this->loadDataFromResult($row);
                array_push($undertakes,$undertake);
            }
            return $undertakes;
        }
        else
            return null;
    }

    //从结果集中构建出undertake对象
    private function loadDataFromResult($row){
        $undertake = new Undertake();
        $undertake->setId($row[self::FIELD_ID]);
        $undertake->setUserId($row[self::FIELD_USER_ID]);
        $undertake->setStageId($row[self::FIELD_STAGE_ID]);
        $undertake->setStartTime($row[self::FIELD_START_TIME]);
        $undertake->setEndTime($row[self::FIELD_END_TIME]);
        $undertake->setStatus($row[self::FIELD_STATUS]);
        $undertake->setContractTime($row[self::FIELD_CONTRACT_TIME]);
        return $undertake;
    }

}
